#!/bin/bash
# This script installs various rpm patches needed for RH16

EXITVAL=0
MD5FILE=/tmp/md5.$$
RESULT=/tmp/res.$$
CNFILE=/tmp/cn.$$

IMG_BASE=/usr/local/hsc_install.images
OPENSSL=/usr/bin/openssl
MD5SUM=/usr/bin/md5sum
VERIFY=/opt/hsc/sbin/verify
DIFF=/usr/bin/diff
FIND=/usr/bin/find
ECHO=/bin/echo
SORT=/bin/sort
CUT=/usr/bin/cut
RM=/bin/rm

InstallUpdates() {
   if [ -f $IMG_BASE/images/.signature ]; then
     typeset -i cver
     typeset -i dver
     cver=`/opt/hsc/bin/hsc version | grep Version | cut -d':' -f 2`
     dver=`cat $IMG_BASE/images/.signature | cut -d' ' -f 2`
     if [ $cver -eq $dver ]; then
        if [ -x $IMG_BASE/images/installImages ]; then
           $IMG_BASE/images/installImages $IMG_BASE/images
           serviceRC=$?
           if [ $serviceRC -ne 0 ]; then
              EXITVAL=6
           fi
        else
           echo "Install script not found" 1>&2
           EXITVAL=7
        fi
     else
        echo "Incompatible service package" 1>&2
        EXITVAL=8
     fi
   else
     echo "Missing Signature file" 1>&2
     EXITVAL=9
   fi
}

source=`/usr/bin/dirname $0`
if [ "$source" = "/media/cdrom/images" ]
then
    IMG_BASE=/media/cdrom
fi

echo "Verifying Certificate Information"
/opt/hsc/sbin/AuthImage $IMG_BASE
if [ $? -eq 0 ]; then
    $RM -f $MD5FILE
    cd $IMG_BASE
    echo "Authenticating Install Packages"
    $FIND images -type f -exec $MD5SUM {} \; >> $MD5FILE
    $SORT $MD5FILE | $MD5SUM | $CUT -f1 -d " " > $RESULT

    $OPENSSL x509 -subject -noout -in cert.pem |$CUT -f8 -d "=" > $CNFILE
    $DIFF $RESULT $CNFILE > /dev/null 2>&1

    if  [ $? -eq 0 ]; then
        echo "Installing Packages"
        $IMG_BASE/images/installImages $IMG_BASE/images
        InstallUpdates
    else
        $ECHO "Install package corruption. HMC not updated"
        EXITVAL=4
    fi
else
    $ECHO "Authentication Failure. HMC not updated"
    $ECHO "Corrupted install image or incorrect time on HMC"
    $ECHO "Please verify the date/time of the hmc and retry"
    EXITVAL=5
fi

rm -f $MD5FILE $RESULT $CNFILE

exit $EXITVAL
